package com.google.code.drift.dialog;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.widget.EditText;

import com.alibaba.fastjson.JSONObject;
import com.google.code.drift.R;
import com.google.code.drift.api.AppSkyApp;
import com.google.code.drift.utils.JsonFactory;
import com.google.code.drift.utils.CommonUtils;
import com.google.code.drift.utils.PreferencesProxy;
import com.google.code.drift.utils.PreferencesProxy.PrefKey;

public class EnterNickAndSexDialog extends AlertDialog.Builder {

	private final Context context;

	private EditText edit;

	private String oldNick;

	private AppSkyApp app = null;

	public EnterNickAndSexDialog(Context context) {
		super(context);
		this.context = context;
		app = (AppSkyApp) ((Activity) context).getApplication();
		oldNick = app.getMyInfo().getNick();

		initView();
		initButton();

	}

	/**
	 * 初始化Dialog的View
	 */
	private void initView() {
		edit = new EditText(context);
		if (CommonUtils.isNullString(oldNick)) {
			edit.setHint(R.string.enter_nick_text);
		} else {
			edit.setHint(oldNick);
		}
		setIcon(R.drawable.ic_compose);
		setTitle(R.string.enter_nick_title);
		setView(edit);
	}

	/**
	 * 初始化Dialog的Button，
	 * 
	 * @param getMyInfo
	 *            () 用来设置用户的Nick
	 */
	private void initButton() {

		final int oldSex = app.getMyInfo().getSex();

		String[] sexItem = { "女", "男", "保密" };
		setSingleChoiceItems(sexItem, oldSex, new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				app.getMyInfo().setSex(which);
				PreferencesProxy.putInt(PrefKey.MY_SEX, which);
			}
		});
		setPositiveButton(R.string.ok, new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				String nick = edit.getText().toString();
				if (CommonUtils.isNullString(nick)) {
					if (CommonUtils.isNullString(oldNick)) { // 用户还没有昵称
						app.getMyInfo().setNick(
								context.getString(R.string.default_nick));
					}
				} else { // 用户更改了昵称
					app.getMyInfo().setNick(nick);
					PreferencesProxy.putString(PrefKey.MY_NICK, nick);
				}
				if (oldSex != app.getMyInfo().getSex() || !nick.equals(oldNick)) {
					JsonFactory jsonFactory = JsonFactory.getFactory();
					JSONObject json = jsonFactory
							.makeUpdateInfoJson(app.getMyInfo().getUserId(),
									app.getMyInfo().getNick(), app.getMyInfo()
											.getSex());
					CommonUtils.sendDataToServer(context, json.toJSONString());
				}
			}
		});
		setNegativeButton(R.string.cancel, new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {

				if (oldNick == null) {
					app.getMyInfo().setNick(
							context.getString(R.string.default_nick));
				}
			}
		});
	}

}
